import 'dart:async';
import 'dart:typed_data';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/binding_terminal_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/set_terminal_position_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_address_icon_to_image.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'bean/binding_terminal_response_bean.dart';

/// 查看终端位置页面
class ShowTerminalAddressPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "ShowTerminalAddressPage";
  final TerminalInfoBean terminalInfoBean;
  const ShowTerminalAddressPage({Key key, this.terminalInfoBean})
      : super(key: key);

  @override
  _ShowTerminalAddressPageState createState() => _ShowTerminalAddressPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(
      BuildContext context,  TerminalInfoBean terminalInfoBean) {
    return RouterUtils.routeForFutureResult(
      context,
      ShowTerminalAddressPage(
        terminalInfoBean:terminalInfoBean,
      ),
      routeName: ShowTerminalAddressPage.ROUTER,
    );
  }
}

class _ShowTerminalAddressPageState extends BaseState<ShowTerminalAddressPage> {

  BindingTerminalViewModel _viewModel;
  LatLng _latLng;
  Set<Marker> _markerList;
  GlobalKey _globalKey = GlobalKey();
  bool _initFlag;
  String _position;
  String _gpsAddress;
  @override
  void initState() {
    super.initState();
    _latLng = new LatLng(double.parse(widget?.terminalInfoBean?.gps?.split(",")[0]),
        double.parse(widget?.terminalInfoBean?.gps?.split(",")[1]));
    _viewModel = BindingTerminalViewModel(this);
    _markerList = new Set();
    // _viewModel.getDetailInfoByGps(context, widget?.terminalInfoBean?.gps??"");
    _position = widget?.terminalInfoBean?.position??"";
    _gpsAddress = widget?.terminalInfoBean?.address??"";
    if(StringUtils.isEmpty(_position)){
      _position = _gpsAddress;
    }
    Future((){
      VgToolUtils.removeAllFocus(context);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      if(_initFlag??false){
        return;
      }
      try{
        Future<Uint8List> file = GetWidgetToImage.getInstance(_globalKey).getUint8List();
        file.then((value) => {
          setState((){
            _markerList.add(new Marker(
              position: _latLng,
              icon: BitmapDescriptor.fromBytes(value),
              infoWindowEnable: true,
            ));
            _initFlag = true;
          })
        });
      }on Exception{
      }catch (e){
        print("'!debugNeedsPaint': is not true.");
      }
    });

    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toInfoWidget(widget?.terminalInfoBean),
    );
  }

  Widget _toInfoWidget(TerminalInfoBean terminalInfoBean){
    return Stack(
      children:[
        Positioned(
          top: (ScreenUtils.getStatusBarH(context) + 44 + 10),
          left: (ScreenUtils.screenW(context) - 30)/2,
          child:     TerminalAddressIconToImage(
            globalKeys: _globalKey,
          ),
        ),
        Column(
          children: <Widget>[
            _toTopBarWidget(),
            SizedBox(height: 10,),
            _toMapWidget(terminalInfoBean),
            SizedBox(height: 20,),
            _toPositionTextWidget(),
          ],
        ),

      ],
    );
    // return Column(
    //   children: <Widget>[
    //     _toTopBarWidget(),
    //     SizedBox(height: 10,),
    //     _toMapWidget(terminalInfoBean),
    //   ],
    // );
  }

  Widget _toTopBarWidget(){
    return  VgTopBarWidget(
      title: "摆放位置",
      isShowBack: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  Widget _toMapWidget(TerminalInfoBean terminalInfoBean){
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15),
      height: 220,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: AMapWidget(
          initialCameraPosition: CameraPosition(
            target: _latLng,
            zoom: 17,
          ),
          markers: _markerList,
          scaleEnabled: false,
        ),
      ),
    );
    // return Expanded(
    //   child: AMapWidget(
    //     initialCameraPosition: CameraPosition(
    //       target: _latLng,
    //       zoom: 17,
    //     ),
    //     markers: _markerList,
    //     scaleEnabled: false,
    //   ),
    // );
  }

  Widget _toPositionTextWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        SetTerminalPositionDialog.navigatorPushDialog(context, position: _position,
            onReset: (){
              setState(() {
                _position = _gpsAddress;
                _viewModel.setTerminalPosition(context, widget?.terminalInfoBean?.id,
                    widget?.terminalInfoBean?.hsn, "01", _position);
              });
            },
            onConfirm: (position){
              setState(() {
                _position = position;
                _viewModel.setTerminalPosition(context, widget?.terminalInfoBean?.id,
                    widget?.terminalInfoBean?.hsn, "01", _position);
              });
            }
        );
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Text(
                _position,
                style: TextStyle(
                    fontSize: 14,
                    color: ThemeRepository.getInstance().getTextColor_D0E0F7()
                ),
              ),
            ),
            SizedBox(width: 15,),
            Container(
              height: 21,
              child: Image.asset(
                "images/icon_edit_terminal_position.png",
                width: 10,
              ),
            )
          ],
        ),
      ),
    );
  }

  onMapMoveEnd(){
    setState(() { });
  }
}
